<%--
  Created by IntelliJ IDEA.
  User: LLLzy
  Date: 2025/6/18
  Time: 08:56
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<c:set var="title" value="设备管理"/>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <%@ include file="../common/header.jsp" %>

    <div class="main-content">
        <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
            <h1 class="h2">${title}</h1>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addEquipmentModal">
                <i class="fa-solid fa-plus-circle"></i> 添加设备
            </button>
        </div>

        <!-- 设备概览 -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">设备总数</h5>
                        <p class="card-text display-6">${totalEquipment}</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">运行中</h5>
                        <p class="card-text display-6">${runningEquipment}</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">待维护</h5>
                        <p class="card-text display-6">${maintenanceNeeded}</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">设备利用率</h5>
                        <p class="card-text display-6">${utilizationRate}%</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 设备状态图表 -->
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">设备状态分布</h5>
                        <canvas id="equipmentStatusChart"></canvas>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">设备类型分布</h5>
                        <canvas id="equipmentTypeChart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- 设备列表 -->
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">设备列表</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>设备编号</th>
                                <th>设备名称</th>
                                <th>参数</th>
                                <th>状态</th>
                                <th>修改时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <c:forEach items="${equipmentList}" var="equipment">
                                <tr>
                                    <td>${equipment.equipId}</td>
                                    <td>${equipment.equipName}</td>
                                    <td>${equipment.params}</td>
                                    <td>${equipment.status}</td>
                                    <td><fmt:formatDate value="${equipment.updateTime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
                                    <td>
                                        <button class="btn btn-sm btn-primary" onclick="showEditParamsModal('${equipment.equipId}', '${equipment.params}')">修改</button>
                                    </td>
                                </tr>
                            </c:forEach>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加设备模态框 -->
    <div class="modal fade" id="addEquipmentModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加设备</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="addEquipmentForm">
                        <div class="mb-3">
                            <label class="form-label">设备编号</label>
                            <input type="text" class="form-control" name="code" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">设备名称</label>
                            <input type="text" class="form-control" name="name" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">设备类型</label>
                            <select class="form-select" name="type" required>
                                <option value="CLEANING">清洗设备</option>
                                <option value="DRYING">干燥设备</option>
                                <option value="CUTTING">切割设备</option>
                                <option value="PACKAGING">包装设备</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">负责人</label>
                            <input type="text" class="form-control" name="manager" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">备注</label>
                            <textarea class="form-control" name="notes" rows="3"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="submitAddEquipment()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 设备参数编辑模态框 -->
    <div class="modal fade" id="editParamsModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form id="editParamsForm">
                    <div class="modal-header">
                        <h5 class="modal-title">修改设备参数</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body" id="editParamsBody">
                        <!-- 动态生成参数输入框 -->
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="submitEditParams()">保存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <%@ include file="../common/footer.jsp" %>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script>
        var statusLabels = ${statusLabelsJson};
        var statusData = ${statusDataJson};
        var typeLabels = ${typeLabelsJson};
        var typeData = ${typeDataJson};

        // 设备状态分布图表
        const equipmentStatusCtx = document.getElementById('equipmentStatusChart').getContext('2d');
        new Chart(equipmentStatusCtx, {
            type: 'pie',
            data: {
                labels: statusLabels,
                datasets: [{
                    data: statusData,
                    backgroundColor: [
                        'rgb(40, 167, 69)',
                        'rgb(255, 193, 7)',
                        'rgb(220, 53, 69)'
                    ]
                }]
            },
            options: {
                responsive: true
            }
        });

        // 设备类型分布图表
        const equipmentTypeCtx = document.getElementById('equipmentTypeChart').getContext('2d');
        new Chart(equipmentTypeCtx, {
            type: 'pie',
            data: {
                labels: typeLabels,
                datasets: [{
                    data: typeData,
                    backgroundColor: [
                        'rgb(255, 99, 132)',
                        'rgb(54, 162, 235)',
                        'rgb(255, 205, 86)',
                        'rgb(75, 192, 192)'
                    ]
                }]
            },
            options: {
                responsive: true
            }
        });

        function viewDetails(equipmentId) {
            // 实现查看详情功能
        }

        function updateStatus(equipmentId) {
            // 实现更新状态功能
        }

        function scheduleMaintenance(equipmentId) {
            // 实现安排维护功能
        }

        function submitAddEquipment() {
            // 实现添加设备功能
        }

        let currentEditEquipId = null;
        function showEditParamsModal(equipId, paramsStr) {
            currentEditEquipId = equipId;
            let paramsArr = paramsStr.split(';').filter(Boolean);
            let html = '';
            paramsArr.forEach((item, idx) => {
                // 兼容全角冒号和多余空格
                let [key, value] = item.split(':');
                if (!value && item.includes('：')) { // 兼容全角冒号
                    [key, value] = item.split('：');
                }
                key = key ? key.trim() : '';
                value = value ? value.trim() : '';
                html += `<div class="mb-3"><label class="form-label">${key}</label><input type="text" class="form-control" name="paramValue" data-key="${key}" value="${value}"></div>`;
            });
            $('#editParamsBody').html(html);
            $('#editParamsModal').modal('show');
        }
        function submitEditParams() {
            let paramInputs = $('#editParamsBody input[name="paramValue"]');
            let paramsArr = [];
            paramInputs.each(function() {
                let key = $(this).data('key');
                let value = $(this).val();
                // 允许value为空，但key必须有
                if (key) {
                    paramsArr.push(key + ':' + value);
                }
            });
            let paramsStr = paramsArr.join(';');
            $.ajax({
                url: '${pageContext.request.contextPath}/processing/updateEquipmentParams',
                type: 'POST',
                data: JSON.stringify({equipId: currentEditEquipId, params: paramsStr}),
                contentType: 'application/json',
                success: function(res) {
                    $('#editParamsModal').modal('hide');
                    location.reload();
                },
                error: function() {
                    alert('保存失败，请重试');
                }
            });
        }
    </script>
</body>
</html>
